package cn.gov.lyhdga.first.service.message;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import cn.gov.lyhdga.first.entity.Message;
import cn.gov.lyhdga.first.repository.MessageDao;

//Spring Bean的标识.
@Component
//默认将类中的所有public函数纳入事务管理.
@Transactional
public class MessageService {
	
	private MessageDao messageDao;
	
	public Message getMessage(Long id){
		return messageDao.findOne(id);
	}
	
	public void saveMessage(Message entity){
		messageDao.save(entity);
	}
	
	public void deleteMessage(Long id){
		messageDao.delete(id);
	}
	
	public List<Message> getAllMessage(){
		return (List<Message>) messageDao.findAll();
	}
	
	public Page<Message> getUserMessage(Long userId, Map<String, Object> searchParams, int pageNumber, int pageSize,
			String sortType){
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Specification<Message> spec = buildSpecification(userId, searchParams);
		
		return messageDao.findAll(spec, pageRequest);
	}
	
	/**
	 * create paging request
	 */
	public PageRequest buildPageRequest(int pageNumber, int pageSize, String sortType){
		Sort sort = null;
		if("auto".equals(sortType)){
			sort = new Sort(Direction.DESC, "id");
		}else if("title".equals(sortType)){
			sort = new Sort(Direction.ASC, "title");
		}
		
		return new PageRequest(pageNumber - 1, pageSize, sort);
	}
	
	/**
	 * create dynamic query
	 */
	public Specification<Message> buildSpecification(Long userId, Map<String, Object> searchParams){
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId));
		Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
		return spec;
	}
	
	@Autowired
	public void setMessageDao(MessageDao messageDao){
		this.messageDao = messageDao;
	}
}
